package hanlder

import (
	"comment-master/cache"
	"comment-master/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Like(c *gin.Context) {
	content := c.PostForm("content")
	author := c.PostForm("author")
	if content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Like{
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	redis_key := "like_" + strconv.Itoa(int(data.ID))
	var user models.Like
	models.DB.Where("id = ?", data.ID).Find(&user)
	jsonData, _ := json.Marshal(user)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return
}
